package com.catazy.mvvmlib.base.activity

import android.net.ConnectivityManager
import android.net.NetworkRequest
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.catazy.mvvmlib.base.viewmodel.BaseViewModel
import com.catazy.mvvmlib.net.network.NetState
import com.catazy.mvvmlib.net.network.NetworkCallbackImpl
import com.catazy.mvvmlib.net.network.NetworkStateManager
import java.lang.reflect.ParameterizedType

/**
 * 作者: Tao
 * 日期: 2024/1/24
 * 时间: 16:04
 * 描述: ViewModel基类Activity
 */
abstract class BaseVmActivity<VM : BaseViewModel> : AppCompatActivity() {

    lateinit var mViewModel: VM

    /**
     * 子类实现，传入布局的ID
     */
    abstract fun layoutId(): Int

    /**
     * 子类实现，初始化View
     */
    abstract fun initView(savedInstanceState: Bundle?)

    /**
     * 子类实现，网路状态变化监听
     */
    open fun onNetworkStateChanged(netState: NetState){}

    /**
     * 子类实现，LiveData观察者，规范会代码，所有的LiveData观察者都放在这方法里调用
     */
    open fun initObserver(){}

    /**
     * 子类实现，初始化数据
     */
    open fun initData(){}

    /**
     * 子类实现，显示弹窗
     */
    open fun showLoading(message: String = "请求中..."){}

    /**
     * 子类实现，关闭弹窗
     */
    open fun dismissLoading(){}

    /**
     * 供子类创建View
     */
    open fun initDataBind(): View? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (initDataBind() != null) {
            setContentView(initDataBind())
        } else{
            setContentView(layoutId())
        }
        init(savedInstanceState)
    }

    private fun init(savedInstanceState: Bundle?) {
        // 初始化ViewModel
        initViewModel()
        // 初始化View
        initView(savedInstanceState)
        // 初始化LiveData观察者
        initObserver()
        // 注册网络状态监听
        registerNetworkCallback()
        // ViewModel需要显示弹窗时，通过LiveData发送事件通知Activity显示
        registerUiChange()
        // 初始化数据
        initData()
    }

    @Suppress("UNCHECKED_CAST")
    private fun initViewModel() {
        // actualTypeArguments[0], 相当于取BaseVmActivity<VM : BaseViewModel>的泛型第一个参数VM : BaseViewModel，
        val type = javaClass.genericSuperclass as ParameterizedType
        val argument = type.actualTypeArguments[0]
        mViewModel = ViewModelProvider(this)[argument as Class<VM>]
    }

    private fun registerNetworkCallback() {
        val networkCallbackImpl = NetworkCallbackImpl()
        val request = NetworkRequest.Builder().build()
        val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
        cm.registerNetworkCallback(request, networkCallbackImpl)
        NetworkStateManager.instance.mNetworkStateCallback.observe(this) {
            onNetworkStateChanged(it)
        }
    }

    private fun registerUiChange() {
        // 显示弹窗
        mViewModel.loadingChange.showDialog.observe(this) {
            showLoading(it)
        }
        // 关闭弹窗
        mViewModel.loadingChange.dismissDialog.observe(this) {
            dismissLoading()
        }
    }
}